<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Model\User;
use App\Model\UserToken;
use App\Service\Lock;
use App\Service\PlayService;
use Hyperf\HttpServer\Contract\RequestInterface;

class IndexController extends AbstractController
{

    public function init(RequestInterface $request)
    {
        $header = $this->request->getHeader('token');
        if (!isset($header) || empty($header)) {
            return $this->output(400, 'Token缺失');
        }
        $token = $header[0];
        $con = UserToken::checkUser($token);
        if ($con['code'] !== 0) {
            return $this->output(400, $con['msg']);
        }
        $info = User::userInfo($con['data']['uid']);
        // 机器人账户检查
        $robot_conf = config('robot');
        if (in_array($info['account'], $robot_conf['robots'])) {
            return $this->output(400, '非法账户不能登录');
        }
        $this->cacheUser($token, $info);//缓存用户信息

        $signData = PlayService::index($info['account']);

        $signListdata = PlayService::signList($info['account']);

        $returnData = [
            'user' => $info,
            'sign' => $signData,
            'sign_list' => $signListdata,
        ];
        return $this->output(1, 'ok', $returnData);
    }


    /**
     * 进入接口
     */
    public function entry(RequestInterface $request)
    {
        $token = $request->input('token');
        if (empty($token)) {
            return ERROR('Token缺失');
        }
        $con = UserToken::checkUser($token);
        if ($con['code'] !== 0) {
            return $this->output(400, $con['msg']);
        }
        $info = User::userInfo($con['data']['uid']);
        // 机器人账户检查
        $robot_conf = config('robot');
        if (in_array($info['account'], $robot_conf['robots'])) {
            return $this->output(400, '非法账户不能登录');
        }
        $this->cacheUser($token, $info);//缓存用户信息
        return $this->output(1, 'ok', $info);
    }


    /**
     * 缓存数据
     * @param $key
     * @param $data
     * @param int $expire
     */
    private function cacheUser($key, $data, $expire = 86400)
    {
        $redis = redis();
        $tokenKey = 'token:'.$key;
        $redis->set($tokenKey, json_encode($data, JSON_UNESCAPED_SLASHES), $expire);
    }

}
